﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using frmPrincipalTestes;

namespace frmPrincipal
{
    public partial class frmCadFornecedores : Form
    {
        private StandardDBConnection standardDBConnection = new StandardDBConnection();
        private bool isInclusion;
        private string lastSupplierName;

        //Form
        public frmCadFornecedores()
        {
            InitializeComponent();
        }
        public frmCadFornecedores(string cnpj)
        {
            InitializeComponent();
            this.txtCNPJ.Text = cnpj;
        }
        private void frmCadFornecedores_Close(object sender, EventArgs e)
        {
            standardDBConnection.cnn.Close();
            standardDBConnection.cnn.Dispose();
        }

        //Geral
        public string GetLastSupplierName()
        {
            return lastSupplierName;
        }

        private void CleanFieldsData()
        {
            txtNome.Text = "";
            txtEmail.Text = "";
            txtTelefone.Text = "";
        }
        private void CleanFields()
        {
            CleanFieldsData();
            btnDelete.Enabled = false;
            txtCNPJ.Text = "";
            txtCNPJ.Enabled = true;
            txtCNPJ.Focus();
            txtSearchByCode.Text = "";
            txtSearchByCode.Enabled = true;
            txtSearchByCode.Focus();
        }
        private bool IsFieldsFilled()
        {

            bool bPreenchido = true;

            if (txtNome.Text.Trim() == "")
            {
                txtNome.BackColor = Color.LightBlue;
                bPreenchido = false;

            }

            else
                txtEmail.BackColor = Color.White;

            if (txtEmail.Text.Trim() == "")
            {
                txtEmail.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtEmail.BackColor = Color.White;

            if (txtTelefone.Text.Trim() == "")
            {
                txtTelefone.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtTelefone.BackColor = Color.White;

            return (bPreenchido);
        }

        //Pesquisa de Fornecedor
        private void PesquisaFornecedor()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText;

            if (!Testes.ValidCNPJ(txtSearchByCode.Text))
            {
                MessageBox.Show("Forneça um código válido!", "Cadastro de Fornecedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


            this.Cursor = Cursors.WaitCursor;

            CleanFieldsData();

            sqlCommandText = "SELECT * FROM fornecedor WHERE cnpj = '" + txtSearchByCode.Text + "' ";
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            databaseDataReader = sqlCommand.ExecuteReader();

            if (!databaseDataReader.HasRows)
            {
                isInclusion = true;
                if (Testes.ValidCNPJ(txtSearchByCode.Text))
                {
                    MessageBox.Show("Não Encontrado, o cnpj fornecido será usado para cadastro.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtCNPJ.Text = txtSearchByCode.Text;
                }
                else
                    MessageBox.Show("CNPJ inválido!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                btnDelete.Enabled = false;
            }
            else
            {
                isInclusion = false;
                databaseDataReader.Read();
                txtCNPJ.Text = databaseDataReader["cnpj"].ToString();
                txtNome.Text = databaseDataReader["nome_forn"].ToString();
                txtEmail.Text = databaseDataReader["email_forn"].ToString();
                txtTelefone.Text = databaseDataReader["tel_forn"].ToString();
                btnDelete.Enabled = true;
                txtCNPJ.Enabled = false;
            }

            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            PesquisaFornecedor();
        }
        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                PesquisaFornecedor();
        }

        //Botões
        private void btnDelete_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;
            DialogResult resp;

            resp = MessageBox.Show("Confirma a exclusão do registro?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (resp == DialogResult.Yes)
            {

                this.Cursor = Cursors.WaitCursor;

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommandText = "DELETE FROM fornecedor WHERE cnpj = " + txtCNPJ.Text;
                sqlCommand.CommandText = sqlCommandText;
                sqlCommand.ExecuteNonQuery();

                MessageBox.Show("Exclusão efetuada com sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                CleanFields();
                sqlCommand.Dispose();

                this.Cursor = Cursors.Default;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;

            if (!IsFieldsFilled())
            {
                MessageBox.Show("Preencha os campos destacados!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            if (isInclusion)
            {

                sqlCommandText = "INSERT INTO fornecedor (cnpj, nome_forn, email_forn, tel_forn)";
                sqlCommandText = sqlCommandText + " values ('" + txtCNPJ.Text + "', ";
                sqlCommandText = sqlCommandText + "'" + txtNome.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtEmail.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtTelefone.Text + "') ";
            }
            else
            {
                sqlCommandText = "update fornecedor ";
                sqlCommandText = sqlCommandText + "set nome_forn = '" + txtNome.Text + "',";
                sqlCommandText = sqlCommandText + " email_forn = '" + txtEmail.Text + "',";
                sqlCommandText = sqlCommandText + " tel_forn = '" + txtTelefone.Text + "'";
                sqlCommandText = sqlCommandText + " WHERE cnpj = '" + txtCNPJ.Text + "' ";
            }

            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            sqlCommand.ExecuteNonQuery();

            lastSupplierName = txtNome.Text;
            MessageBox.Show("Gravação Efetuada com Sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            CleanFields();
            sqlCommand.Dispose();

            this.Cursor = Cursors.Default;
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            CleanFields();
        }

    }
}

